<!-- eslint-disable n/no-extraneous-import -->
<!--
 * @Author: chengjiang
 * @Date: 2025-04-14 20:39:25
 * @Description:
-->
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { VuePrintNext } from 'vue-print-next';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash-es';

import { type OrderData, updateOrderPrintStatusApi } from '#/api/inout/order';
import { numToChinessCap } from '#/utils/number';

import { ceilNumber, type InvoiceData, toSafeNumber } from './models/print';

defineOptions({ name: 'MyPrintIn' });

// props
const props = defineProps<{
  orderdatas?: OrderData[];
}>();

console.log('invoiceData', props.orderdatas);

const ivDataTemplate: InvoiceData = {
  id: 0,
  code: 'PG202500520',
  date: '2025/05/20',
  orderUserName: '罗路章', // todo 获取用户名
  approveUserName: '',
  getUserName: '',
  seller: {
    address: '深圳市罗湖区田贝西路水贝万山珠宝园D座五楼011',
    name: '',
    phone: '133-9281-6562',
    // taxId: '123456789012345678',
  },
  buyer: {
    desc: 'PGGOLD_DESCRIPTION',
    name: '李四',
  },
  items: [
    {
      desc: '下了订单',
      name: 'Au9999',
      price: 123,
      sort: 1,
      type: '千足料',
      totalFee: 123.12,
      unit: 'g',
      weight: 12.85,
      id: 1,
    },
    {
      desc: '下了订单...',
      name: 'Au',
      price: 123,
      sort: 2,
      type: '足金',
      totalFee: 13.12,
      unit: 'g',
      weight: 1.85,
      id: 2,
    },
  ],
  type: '入库单',
  title: '盘庚金业',
  erlian: '红联（客户）',
  totalWeight: 123,
  totalFee: 123.12,
  yilian: '白联（收发）',
  sanlian: '蓝联（财务）',
};

const invoiceDatas = ref<InvoiceData[]>([
  {
    id: 0,
    code: 'PG202500520',
    date: '2025/05/20',
    orderUserName: '罗路章', // todo 获取用户名
    approveUserName: '',
    getUserName: '',
    seller: {
      address: '深圳市罗湖区田贝西路水贝万山珠宝园D座五楼011',
      name: '',
      phone: '133-9281-6562',
      // taxId: '123456789012345678',
    },
    buyer: {
      desc: 'PGGOLD_DESCRIPTION',
      name: '李四',
    },
    items: [
      {
        desc: '下了订单',
        name: 'Au9999',
        price: 123,
        sort: 1,
        type: '千足料',
        totalFee: 123.12,
        unit: 'g',
        weight: 12.85,
        id: 1,
      },
      {
        desc: '下了订单...',
        name: 'Au',
        price: 123,
        sort: 2,
        type: '足金',
        totalFee: 13.12,
        unit: 'g',
        weight: 1.85,
        id: 2,
      },
    ],
    type: '入库单',
    title: '盘庚金业',
    erlian: '红联（客户）',
    totalWeight: 123,
    totalFee: 123.12,
    yilian: '白联（收发）',
    sanlian: '蓝联（财务）',
  },
]);

onMounted(() => {
  if (props.orderdatas !== undefined && props.orderdatas.length > 0) {
    // invoiceDatas.value.push(...invoiceDatas.value);
    invoiceDatas.value = [];
    let i = 0;
    props.orderdatas.forEach((item) => {
      const tmp: InvoiceData = cloneDeep(ivDataTemplate);
      tmp.buyer.name = item.customerName;
      tmp.buyer.desc = item.remark;
      tmp.code = item.orderNo;
      tmp.date = dayjs(item.processTime).format('YYYY/MM/DD');
      tmp.items = [];
      tmp.totalFee = 0;
      tmp.totalWeight = 0;
      tmp.id = item.id;
      item.orderDetailDTOList.forEach((itemdetail) => {
        tmp.items.push({
          id: itemdetail.id,
          // name: itemdetail.name,
          type: itemdetail.name,
          weight: itemdetail.weight,
          price: itemdetail.processFee,
          totalFee: ceilNumber(itemdetail.weight * itemdetail.processFee),
          desc: itemdetail.remark,
          sort: ++i,
        });
        tmp.totalFee! += itemdetail.processFeeTotal;
        tmp.totalWeight += toSafeNumber(itemdetail.weight);
      });
      invoiceDatas.value.push(tmp);
    });
  }
});

function handlePrint() {
  const a = new VuePrintNext({
    el: '#MyPrintIn',
    popTitle: '打印-盘庚金',
    // preview: true,
    // extraCss: 'body {padding: 20px}',
    /* 其他参数 */
    beforeOpenCallback: () => {
      console.log('beforeOpenCallback');
      invoiceDatas.value.forEach(async (item) => {
        await updateOrderPrintStatusApi(item.id)
          .then(() => {
            console.log('updateOrderPrintStatusApi');
          })
          .catch(() => {
            message.error('更新打印状态失败');
          });
      });
    },
  });
  console.log(a);
}
</script>

<template>
  <div>
    <!-- 发票操作栏 -->
    <div>
      <a-button class="m-5" type="primary" @click="handlePrint">
        打印
      </a-button>
    </div>
    <div
      v-for="invoiceData in invoiceDatas"
      id="MyPrintIn"
      :key="invoiceData.code"
      :bordered="true"
    >
      <div :bordered="true" class="invoice-container">
        <!-- 发票主体 -->
        <div id="invoice-content" class="invoice-content">
          <!-- 发票头 -->
          <div class="invoice-header">
            <h1 class="flex justify-center space-x-2 text-3xl font-bold">
              <span v-for="(val, index) in invoiceData.title" :key="index">
                {{ val }}
              </span>
            </h1>
          </div>
          <h1 class="flex justify-center space-x-2 text-lg">
            <span v-for="(val, index) in invoiceData.type" :key="index">{{
              val
            }}</span>
          </h1>
          <!-- 买卖双方信息 -->
          <div class="flex justify-between space-x-2 text-base">
            <span> 公司地址：{{ invoiceData.seller.address }} </span>
            <span>手机号：{{ invoiceData.seller.phone }}</span>
            <span>
              NO：<span class="border-b border-dashed border-black">
                {{ invoiceData.code }}
              </span>
            </span>
          </div>
          <div class="flex justify-between space-x-2 text-base">
            <span class="w-1/2">
              客户名称：
              <span class="w-40 border-b border-dashed border-black">
                {{ invoiceData.buyer.name }}
              </span>
            </span>
            <span>
              备注：
              <span class="w-40 border-b border-dashed border-black">
                {{ invoiceData.buyer.desc }}
              </span>
            </span>
            <span>
              日期：
              <span class="w-20 border-b border-dashed border-black">
                {{ invoiceData.date }}
              </span>
            </span>
          </div>
          <!-- 商品明细表格 -->
          <table class="mt-1 w-full table-auto text-center text-base">
            <thead>
              <tr class="border border-black">
                <th class="w-1/9 border-r border-black">序号</th>
                <th class="w-1/3 border-r border-black">类型</th>
                <th class="w-1/9 border-r border-black">重量(克)</th>
                <th class="w-1/9 border-r border-black">工费(元/克)</th>
                <th class="w-1/9 border-r border-black">工费小计</th>
                <th class="w-2/9">备注</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="item in invoiceData.items"
                :key="item.id"
                class="mb-1 border border-black"
              >
                <td class="border-r border-black">{{ item.sort }}</td>
                <td class="border-r border-black">{{ item.type }}</td>
                <td class="border-r border-black">{{ item.weight }}</td>
                <td class="border-r border-black">{{ item.price }}</td>
                <td class="border-r border-black">{{ item.totalFee }}</td>
                <td>{{ item.desc }}</td>
              </tr>
              <tr class="border border-black">
                <td class="border-r border-black" colspan="2">合计</td>
                <td class="border-r border-black">
                  {{ invoiceData.totalWeight }}
                </td>
                <td class="border-r border-black"></td>
                <td class="border-r border-black">
                  {{ invoiceData.totalFee }}
                </td>
                <td></td>
              </tr>
            </tbody>
          </table>
          <!--  -->
          <div class="ml-5 text-base">
            <span class="w-1/3">
              结算金额（大写）：{{ numToChinessCap(invoiceData.totalFee) }}
            </span>
          </div>
          <div class="space-y mt-1 text-base">
            <p>温馨提示：</p>
            <p>1、客户承诺交付的物品物料是合法所有；</p>
            <p>2、此单据是双方认同有效的凭据。</p>
          </div>
          <!-- 开单人，审核人，提货人  -->
          <div class="mt-1 flex justify-start space-x-2 text-base">
            <span class="w-1/3">制单人：{{ invoiceData.orderUserName }} </span>
            <span class="w-1/3">交货人：{{ invoiceData.getUserName }} </span>
          </div>
          <div class="mt-1 flex justify-center space-x-2 text-base">
            <span> 一联：{{ invoiceData.yilian }} </span>
            <span>二联：{{ invoiceData.erlian }}</span>
            <span> 三联：{{ invoiceData.sanlian }} </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.invoice-container {
  margin: 20px auto;

  .invoice-content {
    padding: 10px 20px;
    border: 2px solid #000;
  }
}
// @page {
//   size: A5;
//   // size: auto A5;
//   // size: 241mm 479mm;
//   margin: 0 10mm;
// }
@media print {
  .section {
    page-break-after: always;
  }
  .invoice-container {
    background: #fff;
    .invoice-content {
      border: none;
    }
  }
}
</style>
